<!--
	作者：offline
	时间：2019-04-25
	描述：对账统计报表
-->
<template>
	<div class="m-view-accountCheckReport m-window">
		<div class="m-condition">
            <el-row :gutter="10" v-if="accountType==1">
                <el-col :span="2" :offset="20">
					<el-button type="primary" @click="searchReport(1)">查询</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="searchReport(2)">导出</el-button>
				</el-col>
            </el-row>
			<el-row :gutter="10">
				<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="6">
						<el-form-item :label="label" class="rightItem">
							<el-select
								value-key="id"
								v-model="searchForm.companyCode"
								:placeholder="`请选择${label}`"
								@change="companyChange"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6" v-if="accountType==1">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="searchForm.supplierName"
								clearable
								@focus="showSupplierDialog"
								readonly
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave"
							>
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="对账期间" class="rightItem">
							<el-date-picker
								v-model="searchForm.startMonth"
								type="month"
								placeholder="开始月"
								value-format="yyyy-MM"
								:clearable="false"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="searchForm.endMonth"
							type="month"
							:clearable="false"
							placeholder="结束月"
							value-format="yyyy-MM"
						></el-date-picker>
					</el-col>
                    <el-col :span="accountType==4?4:3">
						<el-form-item label="查询模式" class="rightItem">
							<el-select v-model="searchType" placeholder="请选择" @change="typeChange">
								<el-option
									v-for="item in searchOption"
									:key="item.key"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
                    <el-col :span="2" :offset="20" v-if="accountType==4">
					<el-button type="primary" @click="searchReport(1)">查询</el-button>
				</el-col>
				<el-col :span="2" v-if="accountType==4">
					<el-button type="primary" @click="searchReport(2)">导出</el-button>
				</el-col>
				</el-form>
			</el-row>
		</div>
		<div class="m-tabelHeader">
			<span v-show="searchType=='summary'">对账公司:&nbsp&nbsp{{accountCompany}}</span>
			<span style="margin-left:10px" v-show="searchType=='summary'">对账期间:&nbsp&nbsp{{accountDate}}</span>
			<span style="margin-left:10px">
				金额合计:
				<span style="color:red">{{accountMoney}}</span>元
			</span>
		</div>
		<!--会对情况统计列表-->
		<div class="m-agTable m-bottom m-top3">
			<agGridComponents
				ref="reportGrid"
				:isColFit="isColFit"
				:getGridOptions="reportGridOptions"
				:getColumnDefs="reportColumnDefs"
			></agGridComponents>
		</div>
		<!-- 分页组件 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 供应商弹窗 -->
		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<srmSupplierInfo ref="srmSupplierInfo" :layout="layout" @setSrmSupplierInfo="setSrmSupplierInfo"></srmSupplierInfo>
		</el-dialog>
		<!-- 查看历史金额弹窗 -->
		<el-dialog
			title="历史对账金额"
			v-if="historyVisible"
			:visible.sync="historyVisible"
			width="70%"
			:before-close="historyDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			:inline-message="true"
		>
			<div class="m-chart">
				<ve-line
					:loading="dataLoading"
					width="100%"
					style="float:right;height:350px;margin-top:10px"
					:data="lineData"
					:settings="chartSettingsLine"
					:extend="extend"
					:mark-line="markLine"
					:mark-point="markPoint"
					:toolbox="toolbox"
				></ve-line>
			</div>
			<div slot="footer" class="dialog-footer"></div>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api"
import constant from "@/public/constant"
import localeText from "@/i18n/agGridText";
import authInfo from "@/public/authInfo"
import Msg from "@/public/message"
import srmSupplierInfo from "@/components/srmSupplierInfo.vue"
import agGridComponents from "@/components/agGridComponents.js"
import Vue from "vue"
import serviceTime from "@/public/serverTime.js"
import { exportExcel } from 'lesso-common/public/utils'


const operator = Vue.extend({
	template: `<span>
		<el-button type="text" @click="viewHistory" class="rendererClass" size="mini" >查看</el-button>
		</span>`,
	data () {
		return {
			//   delDetailsShow: operator.delDetailsShow
		}
	},
	methods: {
		viewHistory () {
			this.params.context.componentParent.viewHistory(this.params.node);
		}
	}
})

export default {
	data () {
		this.toolbox = {
			feature: {
				magicType: { type: ['line', 'bar'] },
				saveAsImage: {}
			},
			right: 20
		}
		return {
			inputClearBut: false,
			label: '',
			// 查询条件  
			searchForm: {
				companyCode: '',
				startMonth: '',
				endMonth: ''
			},
			rowData: [],
			//查询模式
			searchType: 'summary',
			//表格是否自适应窗口宽度
			isColFit: true,
			//是否显示选择供应商弹窗
			srmSupplierDialogVisible: false,
			//是否显示历史对账金额弹窗
			historyVisible: false,
			layout: {},
			comOptions: [],
			// 分页信息
			pageInfo: {
				current: 1,
				size: 30,
				total: 0
			},
			// 合计金额   
			accountMoney: 0,
			// 对账期间
			accountDate: '',
			// 对账公司
			accountCompany: '',
			// 查询模式下拉
			searchOption: [
				{ key: 1, value: 'summary', label: "汇总" },
				{ key: 2, value: 'detail', label: "明细" }
			],
			accountType: "", //账户类型
			// 历史对账金额弹窗相关数据
			dataLoading: false,
			// 图表设置  
			chartSettingsLine: {
				metrics: ['accountAmount'],
				labelMap: {
					'accountAmount': '对账金额'
				},
				dimension: ['date']
			},
			// 图表数据  
			lineData: {
				columns: ['date', 'accountAmount'],
				rows: []
			},
			extend: {
				series: {
					lineStyle: {
						width: 2
					}
				},
				'xAxis.0.axisLabel.rotate': 45
			},
			// 图例配置  
			legend: {
				right: '20px'
			},
			// 配置图表标线
			markLine: {
				label: {
					show: true,
					position: 'middle',
					formatter: (params) => {
						if (params.value) {
							return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
						} else {
							return 0
						}
					}
				},
				data: [
					{ type: 'average', name: '平均值' }
				]
			},
			// 配置图标标点   
			markPoint: {
				label: {
					show: true,
					position: 'inside',
					formatter: (params) => {
						if (params.value) {
							return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
						} else {
							return 0
						}
					}
				},
				data: [
					{ type: 'max', name: '最大值' },
					{ type: 'min', name: '最小值' }
				]
			},
		}
	},
	beforeMount () {
		this.reportGridOptions = {
			context: { componentParent: this },
			// rowSelection: "single",
			animateRows: true, //排序动画
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			enableCellChangeFlash: true,
			enableRangeSelection: true,
			enableColResize: true,
			localeText: localeText
		}

		//   汇总报表-表格列信息
		this.reportColumnDefs = [
			{ headerName: "供应商", field: "supplierName", width: 180 },
			{
				headerName: "对账金额",
				field: "money",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "")
						return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
					else
						return 0
				}
			},
			{ headerName: "签章人", field: "signer", width: 120 },
			{ headerName: "联系电话", field: "signerPhone", width: 120 },
			{ headerName: "地址", field: "signerAddress", width: 160, tooltipField: 'signerAddress' },
			{
				headerName: "历史走势",
				field: "",
				width: 120,
				cellRendererFramework: operator
			}
		]
		//   明细报表-表格列信息
		this.detailColumnDefs = [
			{ headerName: "供应商", field: "supplierName", width: 180, tooltipField: 'supplierName' },
			{ headerName: "公司", field: "companyName", width: 180, tooltipField: 'companyName' },
			{ headerName: "期间", field: "accountDate", width: 100 },
			{
				headerName: "对账金额",
				field: "money",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "") {
						return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
					} else {
						return params.value = 0
					}
				}
			},
			{ headerName: "签章人", field: "signer", width: 120 },
			{ headerName: "联系电话", field: "signerPhone", width: 120 },
			{ headerName: "地址", field: "signerAddress", width: 160, tooltipField: 'signerAddress' }
		]
	},
	mounted () {
		/*
		 * accountType
		 * 1为内部用户
		 * 4为供应商账户
		 */
		// this.getBtAuth();
		this.accountType = constant.accountType;
		if (this.accountType == 4) {
			const { supplierCode, supplierName } = constant.supplierData;
			this.searchForm.supplierCode = supplierCode
			this.searchForm.supplierName = supplierName
			this.label = '客户'
		} else {
			this.label = '公司'
		}
		this.initDate(this.searchType)
	},
	components: {
		srmSupplierInfo,
		agGridComponents
	},
	methods: {
		// 查看历史对账记录
		viewHistory (node) {
			this.lineData.rows = []
			this.historyVisible = true
			const { companyCode, supplierCode } = node.data
			let params = {
				accountDateStart: this.accountDate.split('~')[0],
				accountDateEnd: this.accountDate.split('~')[1],
				queryType: 'history',
				companyCode,
				supplierCode,
			}
			this.dataLoading = true
			_Api.getAccountBillReport(params).then(({ data }) => {
				this.dataLoading = false
				if (data.code == '1') {
					let result = data.rows.queryResult
					Object.keys(result).sort().forEach(key => {
						let obj = {}
						obj.date = key;
						obj.accountAmount = result[key]
						this.lineData.rows.push(obj)
					})
				} else {
					this.dataLoading = false
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 查询防伪码报表数据
		searchReport (flag) {
			let validat = this.validatQuery(this.searchForm, this.searchType)
			if (flag) this.pageInfo.current = 1
			const { current, size } = this.pageInfo
			const {
				supplierCode,//供应商编码
				companyCode, //公司编码
				startMonth,
				endMonth
			} = this.searchForm
			if (!validat) return
			this.accountDate = `${startMonth}~${endMonth}`
			this.comOptions.forEach(item => {
				if (companyCode == item.companyCode) {
					this.accountCompany = item.companyName
				}
			})
			let params = {
				supplierCode,
				companyCode,
				accountDateStart: startMonth,
				accountDateEnd: endMonth,
				queryType: this.searchType,// summary按订单；detail明细
				currentPage: current,
				pageSize: flag == 2 ? 100000 : size
			}
			this.$refs.reportGrid.loading = true
			// 获取报表数据   
			_Api.getAccountBillReport(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.rowData = data.rows.queryResult
					if (flag == 2) {
						this.exportData()
					} else {
						this.pageInfo.total = data.total
						this.accountMoney = data.rows.totalMoney.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
						this.$refs.reportGrid.gridOptions.api.setRowData(this.rowData)
					}
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
				.catch(err => {
					this.$refs.reportGrid.loading = false
					Msg.showErrorMsg(err.data.message)
				})
		},
		//  验证查询参数
		validatQuery (params, type) {
			const {
				companyCode, //公司编码
				startMonth, //开始月
				endMonth  //结束月
			} = params
			if (!companyCode) {
				Msg.showPopMsg(`请选择${this.label}`)
				return false
			} else if (!startMonth) {
				Msg.showPopMsg('请选择开始月份!')
				return false
			} else if (!endMonth) {
				Msg.showPopMsg('请选择结束月份!')
				return false
			} else if (new Date(startMonth).getTime() - new Date(endMonth).getTime() > 0) {
				Msg.showPopMsg('开始月份不能大于结束月份!')
				return false
			}
			return true
		},
		// 选择公司回调
		companyChange (val) {
			if (this.accountType == 1) {
				this.layout.companyCode = val
				this.layout.auth = true
				this.searchForm.supplierCode = ""
				this.searchForm.supplierName = ""
			}
		},
		// 选择查询模式回调
		typeChange (type) {
			this.searchType = type
			this.pageInfo = {
				current: 1,
				size: 30,
				total: 0
			}
			this.setGirdColumn(type)
			this.searchReport()
		},
		// 输入框清除事件监听
		inputClearSon () {
			this.searchForm.supplierName = ""
			this.searchForm.supplierCode = ""
			this.inputClearBut = false
		},
		// 回显选择的供应商信息
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				const { supplierCode, supplierName } = msg[0]
				this.srmSupplierDialogVisible = false
				this.searchForm.supplierCode = supplierCode
				this.searchForm.supplierName = supplierName
			}
		},
		// 打开供应商弹窗
		showSupplierDialog () {
			let that = this;
			if (!this.layout.companyCode) {
				this.$alert(`提示：请选择${this.label}！`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				this.$refs.content.focus()
				return
			} else {
				this.srmSupplierDialogVisible = true
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search()
				})
			}
		},
		// 关闭供应商弹窗回调
		srmSupplierDialogClose (done) {
			this.$refs.srmSupplierInfo.keyWord = ""
			this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
				this.$refs.srmSupplierInfo.keyWord
			)
			done()
		},
		// 关闭条码信息弹窗
		historyDialogClose () {
			this.historyVisible = false
		},
		// 供应商输入框鼠标移入事件监听
		mouseEnter () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = true
		},
		// 供应商输入框鼠标移出事件监听
		mounseLeave () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = false
		},
		// 每页条数改变回调
		handleSizeChange (size) {
			this.pageInfo.size = size
			this.pageInfo.current = 1
			this.searchReport()
		},
		// 页码改变回调
		handleCurrentChange (current) {
			this.pageInfo.current = current
			this.searchReport()
		},
		// 点击上一页回调
		handlePrevClick (current) {
			this.pageInfo.current = current
		},
		// 点击下一页回调
		handleNextClick (current) {
			this.pageInfo.current = current
		},
		// 根据账户类型获取公司下拉列表
		getCompanyOption () {
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.searchForm.companyCode = data[0].companyCode
				this.searchForm.companyName = data[0].companyName
				this.layout.companyCode = data[0].companyCode
				this.layout.auth = true
				if (this.accountType == 1) {
					this.searchReport(1)
				}
			})
				.catch(err => {
					Msg.showErrorMsg(err)
				});
		},
		// 根据查询模式显示不同列
		setGirdColumn (type) {
			if (type == 'summary') {
				this.$refs.reportGrid.gridOptions.api.setColumnDefs(this.reportColumnDefs)
			} else if (type == 'detail') {
				this.$refs.reportGrid.gridOptions.api.setColumnDefs(this.detailColumnDefs)
			}
		},
		// 初始化查询时间
		initDate () {
			// 日期范围默认30天内
			serviceTime.getServiceTime().then((serviceTime) => {
				let startDate = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30 * 3).Format('yyyy-MM')
				let endDate = serviceTime.Format("yyyy-MM")
				this.searchForm.startMonth = startDate
				this.searchForm.endMonth = endDate
				this.getCompanyOption()
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		// 导出列表数据
		exportData () {
			let excelData = []
			let fileName = this.searchType == "summary" ? `${this.accountDate}会对汇总报表.xlsx` : `${this.accountDate}会对明细报表.xlsx`
			this.rowData.forEach(row => {
				if (this.searchType == "summary") {
					excelData.push({
						'供应商': row.supplierName,
						'对账金额': row.money.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
						'签章人': row.signer,
						'联系电话': row.signerPhone,
						'地址': row.signerAddress
					})
				} else {
					excelData.push({
						'供应商': row.supplierName,
						'公司': row.companyName,
						'期间': row.accountDate,
						'对账金额': row.money.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
						'签章人': row.signer,
						'联系电话': row.signerPhone,
						'地址': row.signerAddress
					})
				}
			})
			let params = {
				data: excelData,
				fileName: fileName
			}
			exportExcel(params)
		}
	},
}
</script>

<style>
</style>